package com.ice.day726.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author ice2020x
 * @Date 2022-08-16 11:25
 * @Description: 模拟CAS的ABA问题   被修改了数据但是主线程没有发现
 */
public class CASABADemo {

    public static AtomicInteger id = new AtomicInteger(1);
    public static void main(String[] args) {

        Thread main = new Thread(()->{
            System.out.println("操作线程："+Thread.currentThread().getName()+"操作线程，初始值为"+id);
            try {
                int expect = id.get();
                int newNum = expect+1;
                Thread.sleep(2000);
                boolean b = id.compareAndSet(expect, newNum);
                System.out.println("操作线程："+Thread.currentThread().getName()+"cas操作为:"+b);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"主线程");

        Thread order = new Thread(()->{
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            id.incrementAndGet();
            System.out.println("操作线程："+Thread.currentThread().getName()+"操作线程，现在值为"+id);
            id.decrementAndGet();
            System.out.println("操作线程："+Thread.currentThread().getName()+"操作线程，现在值为"+id);
        },"辅助线程");

        main.start();
        order.start();
    }
}
